<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    #box{
        width: 100px;
        height: 100px;
        background-color: red;
    }
</style>
<body>
    <div id="box" draggable="true"></div>


    <script>
        const box = document.getElementById('box');

        // 鼠标与 box 距离
        let mouseX = 0, x = 0;
        let mouseY = 0, y = 0;

        box.addEventListener('dragstart', function (event) {
            // 获取鼠标与 box 距离
            mouseX = event.offsetX;
            mouseY = event.offsetY;
        });
        box.addEventListener('drag', function (event) {
            // 拖动时，坐标 x = 鼠标与浏览器距离 - 鼠标与 box 距离
            x = event.clientX - mouseX;
            y = event.clientY - mouseY;
            box.style.cssText = `
                position: absolute;
                left: ${x}px;
                top: ${y}px;
            `;
        });
        document.addEventListener('drop', function (event) {
            box.style.cssText = `
                position: absolute;
                left: ${x}px;
                top: ${y}px;
            `;
        });
        document.addEventListener('dragover', function (event) {
            event.preventDefault();
        });
        
    </script>
</body>
</html>